﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DynaPrecision.CommonCollection
{
	public class CycledLinkedList<T>:IEnumerable<T>
	{
		protected class _Node : CycledLinkedListNode<T>
		{
			public T _value
			{
				get { return this.Value; }
				set { this.Value = value; }
			}
			public CycledLinkedListNode<T> _next
			{
				get { return this.Next; }
				set { this.Next = value; }
			}
			public CycledLinkedListNode<T> _previous
			{
				get { return this.Previous; }
				set { this.Previous = value; }
			}
		}
		_Node _head;
		_Node _tail;

		public CycledLinkedListNode<T> Head
		{
			get
			{
				return _head as CycledLinkedListNode<T>;
			}
		}
		public bool IsEnd(CycledLinkedListNode<T> node)
		{
			return System.Object.ReferenceEquals(node, _tail);
		}
		public void AddToTail(T value)
		{
			if (_head == null)
			{
				_head = new _Node { _value = value};
				_head._next = _head;
				_head._previous = _head;
				_tail = _head;
			}
			else
			{
				_Node temp = new _Node { _value = value, _previous = _tail, _next = _head };
				_tail._next = temp;
				_head._previous = temp;
				_tail = temp;
			}
		}
		public void MoveHeadToNext()
		{
			_head = _head._next as _Node;
			_tail = _tail._next as _Node;
		}
		#region IEnumerable<T> Members

		public IEnumerator<T> GetEnumerator()
		{
			var t = Head;
			if (t != null)
			{
				yield return t.Value;
			}
			else { yield break; }
			while (!IsEnd(t))
			{
				t = t.Next;
				yield return t.Value;
				
			}
		}

		#endregion

		#region IEnumerable Members

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return (this as System.Collections.Generic.IEnumerable<T>).GetEnumerator();
		}

		#endregion
	}
}
